package org.ala.shopping_test.shopping_center.repository.order.router;

import java.util.Map;

import org.ala.shopping_test.shopping_center.repository.shard_key.ShoppingOrderShardKey;
import org.ala.shopping_test.shopping_center.repository.shard_key.ShoppingOrderShardKeyRouter;
import org.ala.tiktools.sharddb.mybatis.router.IShardRouter;
import org.ala.shopping_test.shopping_center.repository.order.query.ShoppingOrderQuery;
import org.ala.tiktools.sharddb.mybatis.router.ShardInfo;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.IShardKeyConverter;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.IShardKeyRouter;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.ShardKeyRouteWorker;

/**
 *	分库分表路由器 (shopping_order)
 *  订单总表
 *
 *	@author 骆毅 (ala)
 *	@date 2025-03-19 15:17:51
 */
public class ShoppingOrderQueryRouter implements IShardRouter<ShoppingOrderQuery> {
    /**
     *  分片建路由器
     */
    protected IShardKeyRouter<ShoppingOrderShardKey> router = new ShoppingOrderShardKeyRouter();
    /**
     *  分片建转换器
     */
    protected IShardKeyConverter<ShoppingOrderQuery, ShoppingOrderShardKey> converter = new IShardKeyConverter<ShoppingOrderQuery, ShoppingOrderShardKey>() {
        @Override
        public ShoppingOrderShardKey convert(ShoppingOrderQuery q) {
            return ShoppingOrderShardKey.build()
                    .id(q.getId())
                    .idIn(q.getIdIn())
                    .db(q.getShardDB())
                    .dbs(q.getShardDBIn())
                    .timestamp(q.getCreateTime() != null ? q.getCreateTime() : -1)
                    .timestampGte(q.getCreateTimeGte() != null ? q.getCreateTimeGte() : (q.getCreateTimeGt() != null ? q.getCreateTimeGt() + 1 : -1))
                    .timestampLte(q.getCreateTimeLte() != null ? q.getCreateTimeLte() : (q.getCreateTimeLt() != null ? q.getCreateTimeLt() - 1 : -1))
                    ;
        }

        @Override
        public ShoppingOrderQuery deConvert(ShoppingOrderQuery d, ShoppingOrderShardKey k) {
            ShoppingOrderQuery q = d.copy()
                    .id(k.getId())
                    .idIn(k.getIdIn())
                    .createTime(k.getTimestamp() > 0 ? k.getTimestamp() : null)
                    .createTimeGte(k.getTimestampGte() > 0 ? k.getTimestampGte() : null)
                    .createTimeLte(k.getTimestampLte() > 0 ? k.getTimestampLte() : null);
            q.shardDB(k.getDb()).shardDBIn(k.getDbs());
            return q;
        }
    };


    /**
     * 分库分表
     */
    @Override
    public Map<ShardInfo, ShoppingOrderQuery> route(ShoppingOrderQuery d) {
        return ShardKeyRouteWorker.instance().route(d, router, converter);
    }
}